package com.web;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.HolidayCalendarDTO;
import model.LeaveTypeDTO;

import org.apache.log4j.Logger;

import util.DateUtil;
import util.IdGenerator;
import util.Validation;
import bizlogic.HolidayCalendarManager;
import bizlogic.LeaveTypeManager;
import exception.DAOSystemException;

/**
 * @Pranjal
 * Servlet implementation class LeaveTypeEdit
 */

public class LeaveTypeEdit extends HttpServlet {


	/**
	 * @pranjal
	 */
	private static final long serialVersionUID = 4827014212728524042L;

	private Logger logger = Logger.getLogger(this.getClass());
	private RequestDispatcher leaveTypeJsp;

	@Override
	public void init(ServletConfig config) throws ServletException {
		ServletContext context = config.getServletContext();
		leaveTypeJsp = context.getRequestDispatcher("/admin-leavetype.jsp");
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

			doAdd(req);
			doRefresh(req, resp);

	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String action = null;

			String validation= Validation.validate(req,resp);
			
				if(req.getParameter("action") != null)
					action = (String) req.getParameter("action").trim();
				
				if (action != null && validation=="ERROR:") {
					logger.debug("HomeServlet.doProcess()");
					if (action.equals("delete")) {
						doDelete(req);
						req.setAttribute("state", "delete");	
						doRefresh(req, resp);
					}
					else if (action.equals("add")) {
						doAdd(req);
						req.setAttribute("state", "add");	
						doRefresh(req, resp);
					}
					else if (action.equals("initupdate")) {
						logger.debug("HomeServlet.doInitUpdate()");
						req.setAttribute("state", "initupdate");	
						doInitUpdate(req);
						doRefresh(req, resp);
					}
					else if (action.equals("update")) {
						logger.debug("HomeServlet.doUpdate()");
						req.setAttribute("state", "update");	
						doUpdate(req);
						doRefresh(req, resp);
					}
				}
				else if (validation!="ERROR:")
				{
					for (String name : Collections.list((Enumeration<String>)req.getParameterNames()))
					{
						Object o = req.getAttribute(name);
						if(o!=null)
						{
							req.setAttribute(name, o);
							System.out.println(name);
						}
					}
					req.setAttribute("msg", validation);
					req.setAttribute("state", "invalid");
					doRefresh(req, resp);
				}
				else
				{
					req.setAttribute("state", "none");
					doRefresh(req, resp);
				}
			
	}

	private void doUpdate(HttpServletRequest req) {
		String id = req.getParameter("id");
		try
		{
			LeaveTypeDTO pos = new LeaveTypeDTO();
			pos.setId(req.getParameter("id"));
			pos.setType(req.getParameter("type"));
			LeaveTypeManager posman = new LeaveTypeManager();
			posman.updateLeaveType(pos);
			String msg = "Updated: " + id;
			req.setAttribute("msg", msg);
		}
		catch(DAOSystemException e)
		{
			String msg = "Update Failed: " + e.getShortMessage();
			req.setAttribute("msg", msg);
		}
	}

	private void doInitUpdate(HttpServletRequest req) {
			logger.debug("HomeServlet.doInitUpdate()");
			String id = req.getParameter("id");
			LeaveTypeManager posman = new LeaveTypeManager();
			LeaveTypeDTO pos;
			try {
				pos = posman.findLeaveType(id);
				req.setAttribute("id", pos.getId());
				req.setAttribute("type", pos.getType());
			} catch (DAOSystemException e) {
				String msg = "Cannot Update: " + e.getShortMessage();
				req.setAttribute("msg", msg);
			}
	}

	private void doDelete(HttpServletRequest req) {
		String id = req.getParameter("id");
		LeaveTypeManager posman = new LeaveTypeManager();
		try {
			posman.deleteLeaveType(posman.findLeaveType(id));
		} catch (DAOSystemException e) {
			String msg1 = "DELETE FAILED: " + e.getShortMessage();
			req.setAttribute("msg1", msg1);	
		}
		String msg1 = "DELETED: " + id;
		req.setAttribute("msg1", msg1);		
	}
	
	private void doAdd(HttpServletRequest req) {
		try
		{
			LeaveTypeDTO pos = new LeaveTypeDTO();
			pos.setId(IdGenerator.generateLeaveTypeID().toString());
			pos.setType(req.getParameter("type"));
			LeaveTypeManager posman = new LeaveTypeManager();
			posman.insertLeaveType(pos);
			String msg ="ADDED SUCCESSFULLY!";
			req.setAttribute("msg", msg);
		}
		catch(DAOSystemException e)
		{
			String msg = "Add Failed: " + e.getShortMessage();
			req.setAttribute("msg", msg);
		}
	}

	protected void doRefresh(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {

		LeaveTypeManager posman = new LeaveTypeManager();
		ArrayList<LeaveTypeDTO> posList = new ArrayList<LeaveTypeDTO>();

		try {
			posList = posman.findAllLeaveType();
		} catch (DAOSystemException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		logger.debug("HomeServlet.doRefresh()");
		req.setAttribute("posList", posList);
		leaveTypeJsp.forward(req, resp);
	}

}
